package com.imu.wys.service.impl;


import com.imu.wys.service.VoiceService;
import com.imu.wys.util.XuFeiVoice;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Service("VoiceService")
public class VoiceServiceImpl implements VoiceService {

    @Override
    public Map<String, Object> getScore_Zh(String text, String base64Str) throws Exception {
        XuFeiVoice xuFeiVoice = new XuFeiVoice("ise", "cn_vip", "read_sentence", text, base64Str, new CountDownLatch(1));
        String result = xuFeiVoice.score();
//        System.out.println(result);
        Map<String, Object> resultMap = getXMLMessage_Zh(result);
        return resultMap;
    }

    @Override
    public Map<String, Object> getScore_En(String text, String base64Str) throws Exception {
        XuFeiVoice xuFeiVoice = new XuFeiVoice("ise", "en_vip", "read_sentence", text, base64Str, new CountDownLatch(1));
        String result = xuFeiVoice.score();
        Map<String, Object> resultMap = getXMLMessage_En(result,text);
        return resultMap;
    }


    /***
     * 解析返回的xml信息，返回一个map
     * @param xmlString
     * @return map 包含了种评分，和句子的每个字的读音
     */
    public Map<String, Object> getXMLMessage_Zh(String xmlString) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new StringReader(xmlString));
            Element root = doc.getRootElement();
//            System.out.println(xmlString);
            //依次获得各个节点，由于嵌套关系，所以直接根据名字获取。
            Element read_sentence = root.element("read_sentence");
            //如果鉴定为乱说，则直接返回

            //否则开始获取内容
            Element rec_paper = read_sentence.element("rec_paper");
            Element read_sentenceMain = rec_paper.element("read_sentence");
            Element sentence = read_sentenceMain.element("sentence");

            if (read_sentenceMain.attribute("is_rejected").getValue().equals("true")) {
                resultMap.put("is_rejected", true);
                return resultMap;
            }
            resultMap.put("is_rejected", false);
            //获取各个分数  流利度，完整度，声调， 总分
            Attribute fluency_score = read_sentenceMain.attribute("fluency_score");
            Attribute integrity_score = read_sentenceMain.attribute("integrity_score");
            Attribute phone_score = sentence.attribute("phone_score");
            Attribute tone_score = sentence.attribute("tone_score");
            Attribute total_score = sentence.attribute("total_score");

            resultMap.put("fluency_score", fluency_score.getValue());
            resultMap.put("integrity_score", integrity_score.getValue());
            resultMap.put("phone_score", phone_score.getValue());
            resultMap.put("tone_score", tone_score.getValue());
            resultMap.put("total_score", total_score.getValue());

            //获取word元素列表
            Iterator<Element> wordsElement = sentence.elementIterator();
            //依次遍历word中，每个word为句子中的一个单词
            int x = 0;
            while (wordsElement.hasNext()) {
                Element word = wordsElement.next();  //获取word元素
                String word_content = word.attribute("content").getValue();  //word 中内容，该部分为测平的单词
                Element syll = word.element("syll");
                Iterator<Element> syllsElement = word.elementIterator();       //有的word有多个syll ，所以通过迭代器依次遍历，找到syll的内容与word相同的一个
                while (syllsElement.hasNext()) {
                    Element syll_t = syllsElement.next();
                    String syll_content = syll_t.attribute("content").getValue();
                    if (syll_content.equals(word_content)) {
                        syll = syll_t;
                        break;
                    }
                }
                //将syll中的phone 依次遍历，一般都是声调
                Iterator<Element> phoneElement = syll.elementIterator();
                String content = syll.attribute("content").getValue();
                StringBuilder msg = new StringBuilder();
                while (phoneElement.hasNext()) {
                    Element phone = phoneElement.next();
                    Attribute is_yun = phone.attribute("is_yun");
                    int yunFlag = Integer.parseInt(is_yun.getValue());
                    int perr_msg = Integer.parseInt(phone.attribute("perr_msg").getValue());
                    if (yunFlag == 0) {
                        if (perr_msg == 1) {
                            msg.append("声母错误;");
                        }
                    } else {
                        if (perr_msg == 1) {
                            msg.append("韵母错误;");
                        } else if (perr_msg == 2) {
                            msg.append("调型错误;");
                        } else if (perr_msg == 3) {
                            msg.append("韵母调型错误;");
                        }
                    }
                }
                if (msg.length() == 0) {
                    resultMap.put(x + "", "正确");
                } else {
                    resultMap.put(x + "", msg);
                }
                x++;
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return resultMap;
    }



    public Map<String, Object> getXMLMessage_En(String xmlString,String text) {
        Map<String, Object> resultMap = new HashMap<>();
        SAXReader reader = new SAXReader();
        Document doc = null;
//        System.out.println(xmlString);
        try {
            doc = reader.read(new StringReader(xmlString));
            Element root = doc.getRootElement();
//            System.out.println(root);
            //依次获得各个节点，由于嵌套关系，所以直接根据名字获取。
            Element read_sentence = root.element("read_sentence");
            Element rec_paper = read_sentence.element("rec_paper");
            Element read_chapter = rec_paper.element("read_chapter");
            Element sentence = read_chapter.element("sentence");
            if (read_chapter.attribute("is_rejected").getValue().equals("true")) {
                resultMap.put("is_rejected", true);
                return resultMap;
            }
            resultMap.put("is_rejected", false);

            Attribute fluency_score = read_chapter.attribute("fluency_score");
            Attribute integrity_score = read_chapter.attribute("integrity_score");
            Attribute total_score = sentence.attribute("total_score");

            resultMap.put("fluency_score", fluency_score.getValue());
            resultMap.put("integrity_score", integrity_score.getValue());
            resultMap.put("total_score", total_score.getValue());

            //获取word元素列表
            Iterator<Element> wordsElement = sentence.elementIterator();
            int x=0;
            String[] wordArr = text.split(" ");
            while (wordsElement.hasNext()) {
                Element word = wordsElement.next();
                String content = word.attribute("content").getValue();
                if(!content.equals(wordArr[x])){
                    continue;
                }
                Element syll = word.element("syll");
                String score = syll.attribute("syll_score").getValue();
//                System.out.println(content+"  "+score);
                resultMap.put(x+"",score);
                x++;

            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return resultMap;

    }

    public static void main(String[] args) {
        String t = "i like apple";
        System.out.println(t.split(" ")[2]);
    }


}
